package org.dromara.demo;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;

public class TestGeneralSign {
    //
    public static void main(String[] args) throws Exception {
        //替换成应用的body
        String body="{\"ExternalSystem\":\"EAM_NTXC\",\"billData\":[{\"BatchCode\":\"\",\"MaterialID\":\"TM002331\",\"PlantID\":\"RX00\",\"StorageLocationID\":\"\"}]}";
        //替换成应用的secret
        String secret="af9340c5-73f4-b8d8-5ec3-fea86b427807";
        String signTopRequest = signTopRequest(body, secret);
        System.out.println(signTopRequest);
    }

    /**
     * 对接口请求进行签名。
     */
    public static String signTopRequest(String body, String secret)
            throws IOException {
        // 第一：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        query.append(secret);
        // 第二步：把请求主体拼接在参数后面
        if (body != null) {
            query.append(body);
        }
        // 第三步：使用MD5加密
        byte[] bytes;
        query.append(secret);
        bytes = encryptMD5(query.toString());
        // 第四步：把二进制转化为大写的十六进制
        return byte2hex(bytes);
    }

    /**
     * 把字节流转换为十六进制表示方式。
     */
    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }

    public static byte[] encryptMD5(String data) throws IOException {
        return encryptMD5(data.getBytes("UTF-8"));
    }

    /**
     * 对字节流进行MD5摘要。
     */
    public static byte[] encryptMD5(byte[] data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data);
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse.toString());
        }
        return bytes;
    }
}
